package com.sxj.PDMS.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.mapper.DevelopTheObjectApplicationInformationListMapper;
import com.sxj.PDMS.mapper.StudentMapper;
import com.sxj.PDMS.model.vo.FullPartyMemberInformationListVO;
import com.sxj.PDMS.model.vo.ListOfProbationaryPartyApplicationInformationVO;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.model.entity.DevelopTheObjectApplicationInformationList;
import com.sxj.PDMS.model.entity.ListOfProbationaryPartyApplicationInformation;
import com.sxj.PDMS.model.entity.Student;
import com.sxj.PDMS.service.ListOfProbationaryPartyApplicationInformationService;
import com.sxj.PDMS.mapper.ListOfProbationaryPartyApplicationInformationMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import static com.sxj.PDMS.utils.VerifyUtil.changeDate;

/**
 * @author 503c'j
 * @description 针对表【list_of_probationary_party_application_information(预备党员申请信息列表)】的数据库操作Service实现
 * @createDate 2024-06-14 17:08:05
 */
@Service
@Slf4j
public class ListOfProbationaryPartyApplicationInformationServiceImpl extends ServiceImpl<ListOfProbationaryPartyApplicationInformationMapper, ListOfProbationaryPartyApplicationInformation>
        implements ListOfProbationaryPartyApplicationInformationService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DevelopTheObjectApplicationInformationListMapper developTheObjectApplicationInformationListMapper;
    @Autowired
    private ListOfProbationaryPartyApplicationInformationMapper listOfProbationaryPartyApplicationInformationMapper;

    @Override
    public void registerProbationaryPartyApplicationBatch(List<ListOfProbationaryPartyApplicationInformation> list) {
        log.info("批量注册预备党员对象");
        list.forEach(listOfProbationaryPartyApplicationInformation -> {
            // 1. 校验
            if (StringUtils.isAnyBlank(listOfProbationaryPartyApplicationInformation.getStudentNumber(),
                    listOfProbationaryPartyApplicationInformation.getName(),
                    listOfProbationaryPartyApplicationInformation.getApplicationForm(),
                    listOfProbationaryPartyApplicationInformation.getReasonForApplication(),
                    listOfProbationaryPartyApplicationInformation.getReply(),
                    listOfProbationaryPartyApplicationInformation.getAgreeOrNot())
                    && listOfProbationaryPartyApplicationInformation.getTimeOfApplication() == null &&
                    listOfProbationaryPartyApplicationInformation.getBranchTime() == null &&
                    listOfProbationaryPartyApplicationInformation.getDetermineTheDevelopmentObjectTime() == null &&
                    listOfProbationaryPartyApplicationInformation.getApplicationNumber() == null &&
                    listOfProbationaryPartyApplicationInformation.getDetermineActivistTime() == null &&
                    listOfProbationaryPartyApplicationInformation.getDateOfApplicationForPartyMembership() == null
            ) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
            }
            if (!(listOfProbationaryPartyApplicationInformation.getAgreeOrNot().equals("是") || listOfProbationaryPartyApplicationInformation.getAgreeOrNot().equals("否"))) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "是否同意只能为是或否");
            }
            if (listOfProbationaryPartyApplicationInformation.getStudentNumber().length() != 10) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "的学号有误");
            }
            synchronized (listOfProbationaryPartyApplicationInformation.getStudentNumber().intern()) {
                //看学生表里状态，判断能否插入
                QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("student_number", listOfProbationaryPartyApplicationInformation.getStudentNumber());
                //todo:待优化
                Integer statue = studentMapper.selectOne(queryWrapper).getStatue();
                if (statue < 4) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "不能越级");
                }
                if (statue > 4) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "不能倒退");
                }

                //在发展对象表里存在
                QueryWrapper<DevelopTheObjectApplicationInformationList> queryWrapperDevelop = new QueryWrapper<>();
                queryWrapperDevelop.eq("student_number", listOfProbationaryPartyApplicationInformation.getStudentNumber());

                long developCount = developTheObjectApplicationInformationListMapper.selectCount(queryWrapperDevelop);
                if (developCount <= 0) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "的账号不存在");
                }

                //确定发展对象时间一致
                Date date = developTheObjectApplicationInformationListMapper.selectOne(queryWrapperDevelop).getBranchTime();
                java.sql.Date determineDevelopTime = null;
                try {
                    determineDevelopTime = changeDate(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }


                if (!determineDevelopTime.equals(listOfProbationaryPartyApplicationInformation.getDetermineTheDevelopmentObjectTime())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "的确定发展对象时间不一样");
                }
                //确定积极分子时间一致
                Date determineActivisttime = developTheObjectApplicationInformationListMapper.selectOne(queryWrapperDevelop).getDetermineActivistTime();
                java.sql.Date determineActivistTime = null;
                try {
                    determineActivistTime = changeDate(determineActivisttime);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                if (!determineActivistTime.equals(listOfProbationaryPartyApplicationInformation.getDetermineActivistTime())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "的确定积极分子时间不一样");
                }

                //提交入党申请书的时间
                java.util.Date theDateOfSubmissionOfTheApplication = studentMapper.selectById(listOfProbationaryPartyApplicationInformation.getStudentNumber())
                        .getTheDateOfSubmissionOfTheApplicationForPartyMembership();

                java.sql.Date theDateOfSubmissionOfTheApplicationForPartyMembership = null;
                try {
                    theDateOfSubmissionOfTheApplicationForPartyMembership = changeDate(theDateOfSubmissionOfTheApplication);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }

                if (!theDateOfSubmissionOfTheApplicationForPartyMembership.equals(listOfProbationaryPartyApplicationInformation.getDateOfApplicationForPartyMembership())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "的入党申请书提交日期有误");
                }
                // 在预备党员表里账户不能重复
                QueryWrapper<ListOfProbationaryPartyApplicationInformation> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("student_number", listOfProbationaryPartyApplicationInformation.getStudentNumber());

                Long probationaryPartyApplicationCount = listOfProbationaryPartyApplicationInformationMapper.selectCount(queryWrapper1);

                if (probationaryPartyApplicationCount > 0) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, listOfProbationaryPartyApplicationInformation.getStudentNumber() + "的账号已存在");
                }

                // 2. 插入数据
                int inserted = listOfProbationaryPartyApplicationInformationMapper.insert(listOfProbationaryPartyApplicationInformation);
                if (inserted < 0) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
                }

                // 3.更新发展对象表
                developTheObjectApplicationInformationListMapper.delete(queryWrapperDevelop);
                //4.更新学生表
                Student student = new Student();
                student.setStudentNumber(listOfProbationaryPartyApplicationInformation.getStudentNumber());
                // todo 用常量代替
                student.setStatue(5);
                studentMapper.updateById(student);
            }
        });
    }


    @Override
    public PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO> selectAll(Integer page, Integer pageSize) {
        Integer start = (page - 1) * pageSize;
        List<ListOfProbationaryPartyApplicationInformationVO> listOfProbationaryPartyApplicationInformations = listOfProbationaryPartyApplicationInformationMapper.selectAll(start, pageSize);
        Long total = listOfProbationaryPartyApplicationInformationMapper.selectTotal();
        PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO> pagingQueryResponse = new PagingQueryResponse<>();

        pagingQueryResponse.setRows(listOfProbationaryPartyApplicationInformations);

        pagingQueryResponse.setTotal(total);

        return pagingQueryResponse;
    }

    @Override
    public PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO> listOfProbationaryPartyApplicationInformation(Integer page, Integer pageSize, String studentNumber, String name) {
        Integer start = (page - 1) * pageSize;

        List<ListOfProbationaryPartyApplicationInformationVO> listOfProbationaryPartyApplicationInformations = listOfProbationaryPartyApplicationInformationMapper.selectByNumberOrName(start, pageSize, studentNumber, name);
        Long total = listOfProbationaryPartyApplicationInformationMapper.selectTotalByNumberOrName(studentNumber, name);

        PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO> pagingQueryResponse = new PagingQueryResponse<>();
        pagingQueryResponse.setRows(listOfProbationaryPartyApplicationInformations);
        pagingQueryResponse.setTotal(total);

        return pagingQueryResponse;
    }

    @Override
    public void selectAllStudentAndDownload(String studentNumber, String name, HttpServletResponse response) {
        List<ListOfProbationaryPartyApplicationInformationVO> listOfProbationaryPartyApplicationInformationVOList = listOfProbationaryPartyApplicationInformationMapper.selectAllStudentAndDownload(studentNumber, name);
        if (listOfProbationaryPartyApplicationInformationVOList == null || listOfProbationaryPartyApplicationInformationVOList.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有符合条件的学生");
        }
        // 2.通过POI将数据写入template/预备党员基本信息表.xlsx文件
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/预备党员基本信息表.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(stream);

            // 填充数据
            for (int i = 0; i < listOfProbationaryPartyApplicationInformationVOList.size(); i++) {
                XSSFSheet sheet = excel.getSheetAt(0);
                // 获取第i+1行
                XSSFRow row = sheet.createRow(i + 2);
                ListOfProbationaryPartyApplicationInformationVO listOfProbationaryPartyApplicationInformationVO = listOfProbationaryPartyApplicationInformationVOList.get(i);
                row.createCell(0).setCellValue(listOfProbationaryPartyApplicationInformationVO.getApplicationNumber());
                row.createCell(1).setCellValue(listOfProbationaryPartyApplicationInformationVO.getStudentNumber());
                row.createCell(2).setCellValue(listOfProbationaryPartyApplicationInformationVO.getGrade());
                row.createCell(3).setCellValue(listOfProbationaryPartyApplicationInformationVO.getName());
                row.createCell(4).setCellValue(listOfProbationaryPartyApplicationInformationVO.getDateOfApplicationForPartyMembership());
                row.createCell(5).setCellValue(listOfProbationaryPartyApplicationInformationVO.getDetermineActivistTime());
                row.createCell(6).setCellValue(listOfProbationaryPartyApplicationInformationVO.getDetermineTheDevelopmentObjectTime());
                row.createCell(7).setCellValue(listOfProbationaryPartyApplicationInformationVO.getTimeOfApplication());
                row.createCell(8).setCellValue(listOfProbationaryPartyApplicationInformationVO.getBranchTime());
            }

            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.createRow(listOfProbationaryPartyApplicationInformationVOList.size() + 2);
            row.createCell(0).setCellValue("下载时间:" + new Date().toString());


            // 3.通过输出流将文件下载到浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            excel.write(outputStream);

            // 4.关闭资源
            excel.close();
            outputStream.close();

            log.info("预备党员基本信息表.xlsx下载成功");

        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }
    }
}




